<template>
  <div v-title data-title="微信团购后台管理系统-规则配置" class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="折扣开始时间" prop="discountTimeStart" label-width="88">
        <el-date-picker clearable size="small"
          v-model="queryParams.discountTimeStart"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="选择折扣开始时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="折扣结束时间" prop="discountTimeEnd" label-width="88">
        <el-date-picker clearable size="small"
          v-model="queryParams.discountTimeEnd"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="选择折扣结束时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="折扣类型" prop="discountType">
        <el-select v-model="queryParams.discountType" placeholder="请选择折扣类型" clearable size="small">
          <el-option
            v-for="dict in discountTypeOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:condition:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:condition:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:condition:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:condition:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="conditionList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="ID" align="center" prop="id" v-if="false"/>
      <el-table-column label="折扣开始时间" align="center" prop="discountTimeStart" width="180">
      </el-table-column>
      <el-table-column label="折扣结束时间" align="center" prop="discountTimeEnd" width="180">
      </el-table-column>
      <el-table-column label="团购定金" align="center" prop="eamestMoney" />
      <el-table-column label="折扣类型" align="center" prop="discountType" :formatter="discountTypeFormat" />
      <el-table-column label="折扣金额" align="center" prop="discountMoney" :formatter="moneyFormat" />
      <el-table-column label="折扣百分比(%)" align="center" prop="percent" :formatter="percentFormat">
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:condition:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:condition:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改团购规则设置对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">

        <el-row :gutter="20">
          <el-col :span="10">
            <el-form-item class="w" label="商品搜索/选择" label-width="120px">
              <el-autocomplete
                v-model="goodsName"
                @input="getOrderSupplierList"
                :fetch-suggestions="querySearch"
                placeholder="请输入内容"
                :trigger-on-focus="false"
                @select="handleSelect"
              ></el-autocomplete>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <img v-if="goodsId.length >=19" id="imgx" :src="imageUrl" alt="">
            <img v-else-if='goodsId.length === 0 ' src="../../../assets/images/tpsc.png" alt="">
          </el-col>
        </el-row>
        <br>
        <br>
        <el-row :gutter="20">
          <el-form-item label="选择折扣日期" label-width="120">
          <el-date-picker
            style="width: 600px"
            value-format="yyyy-MM-dd HH:mm:ss"
            v-model="value1"
            type="datetimerange"
            :picker-options="pickerOptions"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            align="right">
          </el-date-picker>
          </el-form-item>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="10">
            <el-form-item label="选择">
        <el-radio v-model="earnest" :label="false" @click="earnestChangeN">无需定金</el-radio>
        <el-radio v-model="earnest" :label="true" @click="earnestChangeY">选择定金</el-radio>
            </el-form-item>
          </el-col>
          <el-col :span="10">
        <el-form-item label="团购定金" prop="eamestMoney" v-show="earnest">
          <el-input v-show="earnest" v-model="form.eamestMoney" placeholder="请输入团购定金">
          <i slot="suffix" style="font-style:normal;margin-right: 10px;">￥</i>
          </el-input>
        </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="10">
        <el-form-item label="折扣类型" prop="discountType">
          <el-select v-model="form.discountType" placeholder="请选择折扣类型">
            <el-option
              v-for="dict in discountTypeOptions"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="dict.dictValue"
            ></el-option>
          </el-select>
        </el-form-item>
          </el-col>
          <el-col :span="10">
        <el-form-item label="折扣金额" prop="discountMoney" v-if="form.discountType == '1'">
          <el-input v-model="form.discountMoney" placeholder="请输入折扣金额">
            <i slot="suffix" style="font-style:normal;margin-right: 10px;">￥</i>
          </el-input>
        </el-form-item>
            <el-form-item label="百分比折扣" prop="percent" v-else-if="form.discountType == '0'" label-width="130">
              <el-input style="width: 200px" v-model="form.percent" placeholder="请输入折扣百分比" >
                <i slot="suffix" style="font-style:normal;margin-right: 10px;">%</i>
              </el-input>
            </el-form-item>
            <el-form-item label="无折扣"  v-else-if="form.discountType == '2'"/>
          </el-col>
        </el-row>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listCondition, getCondition, delCondition, addCondition, updateCondition, exportCondition } from "@/api/system/condition";
import { listGoods, getGoods} from "@/api/system/goods";
import TitleLine from "../../../components/line/index";
import tpsc from '../../../assets/images/tpsc.png'
export default {
  name: "Condition",
  data() {
    return {
      pickerOptions: {
        shortcuts: [{
          text: '最近一周',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近一个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近三个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
            picker.$emit('pick', [start, end]);
          }
        }]
      },
      goodsId: '',
      value1: '',
      imageUrl: '',
      goodsName: '',
      listGoodsList: [],
      restaurants: [],
      earnest: true,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 团购规则设置表格数据
      conditionList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 折扣类型字典
      discountTypeOptions: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        discountTimeStart: undefined,
        discountTimeEnd: undefined,
        eamestMoney: undefined,
        discountType: undefined,
        discountMoney: undefined,
      },
      queryGoodsParams: {
        pageNum: 1,
        pageSize: 10,
        name: undefined,
        goodsTitle: undefined,
        money: undefined,
        images: undefined,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        discountType: [
          { required: true, message: "折扣类型不能为空", trigger: "change" }
        ]
      }
    };
  },
  updated() {
    console.log(this.imageUrl)
  },
  created() {
    this.getOrderSupplierList();
    this.getList();
    this.getDicts("discount_type").then(response => {
      this.discountTypeOptions = response.data;
    });
  },

  watch: {
    'value1': function () {
      this.form.discountTimeStart = this.value1[0]
      this.form.discountTimeEnd = this.value1[1]
    },
    "form.discountType": function () {
      console.log(this.form.discountType)
    }
    // "goodsName": function () {
    //   if (this.goodsName.length === 0) {
    //     var imgx = document.getElementById("imgx");
    //     imgx.setAttribute("src",tpsc)
    //   }
    // }
  },
  methods: {
    moneyFormat(row, column) {
      if (row.discountMoney == '0'||row.discountMoney == '0.00') {
        return "无"
      }else {
        return row.discountMoney
      }
    },
    percentFormat(row, column) {
      if (row.percent == '0'||row.percent == '0.00') {
    return "无"
    }else {
    return row.percent
  }
    },
    getGoodsName(id) {
       getGoods(id).then(response=>{
         console.log(response.data);
           this.goodsId = response.data.id
          this.goodsName =response.data.name
         this.imageUrl = response.data.images
       })
    },
    createFilter(queryString) {
      return (restaurant) => {
        return (restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0);
      };
    },
    //获取id
    handleSelect(item) {
      this.goodsId =  item.id
      this.imageUrl =  item.img
    },

    querySearch(queryString, cb) {
      let restaurants = this.restaurants;
      let results = queryString ? restaurants.filter(this.createFilter(queryString)) : restaurants;
      // 调用 callback 返回建议列表的数据
      cb(results);
    },

    getOrderSupplierList() {
      listGoods(this.queryGoodsParams).then(response => {
        let listGoodsList = response.rows
        this.listGoodsList = []
        for (let item of listGoodsList) {
          this.listGoodsList.push({
            value: item.name,
            img: item.images,
            id: item.id
          })
        }
      });
      this.restaurants = this.listGoodsList;
    },
    earnestChangeY() {
      this.earnest = true;
    },
    earnestChangeN() {
      this.earnest = false;
    },
    /** 查询团购规则设置列表 */
    getList() {
      this.loading = true;
      listCondition(this.queryParams).then(response => {
        this.conditionList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 折扣类型(配置字典)字典翻译
    discountTypeFormat(row, column) {
      return this.selectDictLabel(this.discountTypeOptions, row.discountType);
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.imageUrl = '../../../assets/images/tpsc.png';
      this.value1 = '';
      this.form = {
        id: undefined,
        discountTimeStart: undefined,
        discountTimeEnd: undefined,
        goodsId: undefined,
        percent: undefined,
        eamestMoney: undefined,
        discountType: undefined,
        discountMoney: undefined,
        createBy: undefined,
        createTime: undefined,
        updateBy: undefined,
        updateTime: undefined
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.goodsName = '';
      this.title = "添加团购规则设置";
    },
    setStartAndEnd(start,end) {
      let time = [
    start,end
      ]
      this.value1 = time
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.getGoodsName(row.goodsId);
      this.setStartAndEnd(row.discountTimeStart,row.discountTimeEnd);
      const id = row.id || this.ids
      getCondition(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改团购规则设置";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateCondition(this.form).then(response => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            this.form.goodsId = this.goodsId
            addCondition(this.form).then(response => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm('是否确认删除团购规则设置编号为"' + ids + '"的数据项?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function () {
        return delCondition(ids);
      }).then(() => {
        this.getList();
        this.msgSuccess("删除成功");
      })
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有团购规则设置数据项?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function () {
        return exportCondition(queryParams);
      }).then(response => {
        this.download(response.msg);
      })
    }
  }
};
</script>
<style scoped>
  img {
    width: 100%;
    height: 170px;
    border-radius: 2%;
    border: #040218 solid 0.5px;
    box-shadow: 0 0 20px rgba(30, 30, 30, 0.74);
  }
  .w{
    position: relative;
    top: 70px;
    right: 20px;
  }
</style>
